<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入标题" clearable style="width: 240px" @change="handleQuery" />
      </el-form-item>
      <el-form-item label="所属端" prop="belongTo">
        <el-select v-model="queryParams.belongTo" placeholder="请选择所属端" clearable style="width: 240px" @change="handleQuery">
          <el-option label="用户端" value="1" />
          <el-option label="陪诊端" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px" @change="handleQuery">
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleQuery"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="bannerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" align="center" width="50" v-if="columns.id.visible">
        <template #default="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" :show-overflow-tooltip="true" v-if="columns.title.visible" />
      <el-table-column label="图片" align="center" prop="imageUrl" width="120" v-if="columns.imageUrl.visible">
        <template #default="scope">
          <el-image
            v-if="scope.row.imageUrl"
            :src="scope.row.imageUrl"
            :preview-src-list="[scope.row.imageUrl]"
            style="width: 60px; height: 40px"
            fit="cover"
            :preview-teleported="true"
          />
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="链接地址" align="center" prop="linkUrl" :show-overflow-tooltip="true" v-if="columns.linkUrl.visible">
        <template #default="scope">
          <el-link :href="scope.row.linkUrl" target="_blank" v-if="scope.row.linkUrl">{{ scope.row.linkUrl }}</el-link>
          <span v-else>暂无链接</span>
        </template>
      </el-table-column>
      <el-table-column label="所属端" align="center" prop="belongTo" width="100" v-if="columns.belongTo.visible">
        <template #default="scope">
          <el-tag :type="scope.row.belongTo === 1 ? 'primary' : 'success'">
            {{ scope.row.belongTo === 1 ? "用户端" : "陪诊端" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortOrder" width="80" v-if="columns.sortOrder.visible" />
      <el-table-column label="状态" align="center" prop="status" width="100" v-if="columns.status.visible">
        <template #default="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="有效时间" align="center" prop="validTime" width="200" v-if="columns.validTime.visible">
        <template #default="scope">
          <span v-if="scope.row.startTime && scope.row.endTime"> {{ scope.row.startTime }} - {{ scope.row.endTime }} </span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" v-if="columns.createTime.visible">
        <template #default="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width" v-if="columns.action.visible">
        <template #default="scope">
          <el-tooltip :content="scope.row.isAutoEnable === 1 ? '开启自动启用' : '关闭自动启用'" placement="top">
            <el-button link @click="handleToggleAutoEnable(scope.row)">
              <span :style="{color: scope.row.isAutoEnable === 1 ? '#67C23A' : '#F56C6C', fontSize: '18px'}">
                {{ scope.row.isAutoEnable === 1 ? '√' : '×' }}
              </span>
            </el-button>
          </el-tooltip>
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改轮播图对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" :rules="rules" ref="bannerRef" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" maxlength="255" />
        </el-form-item>

        <el-form-item label="图片" prop="imageUrl">
          <image-upload v-model="form.imageUrl" :limit="1" />
        </el-form-item>

        <el-form-item label="链接地址" prop="linkUrl">
          <el-input v-model="form.linkUrl" placeholder="请输入链接地址" maxlength="512" />
        </el-form-item>

        <el-form-item label="所属端" prop="belongTo">
          <el-radio-group v-model="form.belongTo">
            <el-radio :value="1">用户端</el-radio>
            <el-radio :value="2">陪诊端</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" :max="999" placeholder="排序" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1" :disabled="hasValidDate">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="有效日期" prop="formDateRange">
          <el-date-picker
            v-model="formDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <div style="color:#909399;font-size:14px;line-height:18px;margin:-6px 0 6px 80px;">tips:选择了有效时间，状态默认变为禁用，如需启用，请您手动启用</div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Banner">
import { listBanner, getBanner, delBanner, addBanner, updateBanner, changeBannerStatus, autoEnableBanner } from "@/api/banner/banner";

const { proxy } = getCurrentInstance();

// 响应式数据
const bannerList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

// 列显隐信息
const columns = ref({
  id: { label: "序号", visible: true },
  title: { label: "标题", visible: true },
  imageUrl: { label: "图片", visible: true },
  linkUrl: { label: "链接地址", visible: true },
  belongTo: { label: "所属端", visible: true },
  sortOrder: { label: "排序", visible: true },
  status: { label: "状态", visible: true },
  validTime: { label: "有效时间", visible: true },
  createTime: { label: "创建时间", visible: true },
  action: { label: "操作", visible: true },
});

// 表单数据
const data = reactive({
  form: {},
  // 表单时间范围选择器
  formDateRange: ref([]),
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    belongTo: undefined,
    status: undefined,
    startTime: undefined,
    endTime: undefined,
  },
  rules: {
    title: [
      { required: true, message: "标题不能为空", trigger: "blur" },
      { max: 255, message: "标题长度不能超过255个字符", trigger: "blur" },
    ],
    imageUrl: [{ required: true, message: "图片不能为空", trigger: "blur" }],
    linkUrl: [{ max: 512, message: "链接地址长度不能超过512个字符", trigger: "blur" }],
    belongTo: [{ required: true, message: "所属端不能为空", trigger: "change" }],
    sortOrder: [{ required: true, message: "排序不能为空", trigger: "blur" }],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
  },
});

const { queryParams, form, rules, formDateRange } = toRefs(data);

/** 查询轮播图列表 */
function getList() {
  loading.value = true;
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.startTime = dateRange.value[0] + " 00:00:00";
    queryParams.value.endTime = dateRange.value[1] + " 00:00:00";
  } else {
    queryParams.value.startTime = undefined;
    queryParams.value.endTime = undefined;
  }
  listBanner(queryParams.value).then((res) => {
    loading.value = false;
    bannerList.value = res.rows;
    total.value = res.total;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  queryParams.value.startTime = undefined;
  queryParams.value.endTime = undefined;
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加轮播图";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getBanner(id).then((response) => {
    form.value = response.data;
    // 将startTime和endTime合并为时间范围
    if (form.value.startTime && form.value.endTime) {
      formDateRange.value = [form.value.startTime, form.value.endTime];
    }
    open.value = true;
    title.value = "修改轮播图";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bannerRef"].validate((valid) => {
    if (valid) {
      console.log(formDateRange.value);
      // 将时间范围数据分别赋值给startTime和endTime
      if (formDateRange.value && formDateRange.value.length === 2) {
        form.value.startTime = formDateRange.value[0];
        form.value.endTime = formDateRange.value[1];
      }

      if (form.value.id != undefined) {
        updateBanner(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBanner(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  let confirmText = "";
  let bannerIds = null;
  if (row.id) {
    const index = bannerList.value.findIndex((item) => item.id === row.id);
    confirmText += index + 1 + "、";
    bannerIds = row.id;
  } else {
    ids.value.forEach((id) => {
      const index = bannerList.value.findIndex((item) => item.id === id);
      confirmText += index + 1 + "、";
    });
    bannerIds = ids.value;
  }
  proxy.$modal
    .confirm('是否确认删除轮播图序号为"' + confirmText.slice(0, -1) + '"的数据项？')
    .then(function () {
      return delBanner(bannerIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 轮播图状态修改 */
function handleStatusChange(row) {
  let text = row.status === 1 ? "启用" : "停用";
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.title + '"轮播图吗?')
    .then(function () {
      return changeBannerStatus(row.id, row.status);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.status = row.status === 0 ? 1 : 0;
    });
}

/** 自动启用开关（√/× 列） */
function handleToggleAutoEnable(row) {
  const targetAutoEnable = row.isAutoEnable === 1 ? 0 : 1;
  console.log(targetAutoEnable);
  const confirmText = targetAutoEnable ? '确认要关闭自动启用吗' : '确认要开启自动启用吗';

  proxy.$modal
    .confirm(confirmText + '？')
    .then(function () {
      return autoEnableBanner(row.id, targetAutoEnable);
    })
    .then(() => {
      proxy.$modal.msgSuccess('操作成功');
      getList();
    })
    .catch(() => {});
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    title: undefined,
    imageUrl: undefined,
    linkUrl: undefined,
    belongTo: 1,
    sortOrder: 0,
    status: 1,
    startTime: undefined,
    endTime: undefined,
  };
  // 清空时间范围
  formDateRange.value = [];
  proxy.resetForm("bannerRef");
}

getList();

// 选择了有效日期后，默认将状态设为禁用（可手动改回启用）
const hasValidDate = computed(() => Array.isArray(formDateRange.value) && formDateRange.value.length === 2 && formDateRange.value[0] && formDateRange.value[1]);

watch(
  () => formDateRange.value,
  (val) => {
    if (hasValidDate.value) {
      form.value.status = 0;
    }
  }
);
</script>
